<template>
  <div class="app-container">
    <FHeader :list-query="listQuery" :list.sync="list" :assets-status-dict="assetsStatusDict" :device-type-dict="deviceTypeDict" @filter="handleFilter" @create="handleCreate" />
    <el-table v-if="checkPermission(['admin','network_list','network_all'])" v-loading="listLoading" :data="list" border size="small" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="管理网段">
              <span>{{ props.row.management_segment }}</span>
            </el-form-item>
            <el-form-item label="IP1">
              <span>{{ props.row.ip1 }}</span>
            </el-form-item>
            <el-form-item label="IP2">
              <span>{{ props.row.ip2 }}</span>
            </el-form-item>
            <el-form-item label="资产品牌">
              <span>{{ props.row.brand }}</span>
            </el-form-item>
            <el-form-item label="资产型号">
              <span>{{ props.row.model }}</span>
            </el-form-item>
            <el-form-item label="认证类型">
              <span>{{ props.row.auth_type }}</span>
            </el-form-item>
            <el-form-item label="url">
              <span>{{ props.row.web_url }}</span>
            </el-form-item>
            <el-form-item label="端口">
              <span>{{ props.row.port }}</span>
            </el-form-item>
            <el-form-item label="用户名">
              <span>{{ props.row.username }}</span>
            </el-form-item>
            <el-form-item label="密码">
              <span @click="handleCopy(props.row.password,$event)">{{ props.row.password }}</span>
            </el-form-item>
            <el-form-item label="设备类型">
              <span>{{ props.row.device_type }}</span>
            </el-form-item>
            <el-form-item label="固件版本">
              <span>{{ props.row.os_version }}</span>
            </el-form-item>
            <el-form-item label="上联设备">
              <span>{{ props.row.up_device }}</span>
            </el-form-item>
            <el-form-item label="上联端口">
              <span>{{ props.row.up_link_port }}</span>
            </el-form-item>
            <el-form-item label="机房">
              <template v-if="props.row.idc">
                <span>{{ props.row.idc.name }}</span>
              </template>
            </el-form-item>
            <el-form-item label="机柜">
              <span>{{ props.row.cabinet }}</span>
            </el-form-item>
            <el-form-item label="上架日期">
              <span>{{ props.row.shelves_date }}</span>
            </el-form-item>
            <el-form-item label="维保日期">
              <span>{{ props.row.maintenance_date }}</span>
            </el-form-item>
            <el-form-item label="创建日期">
              <span>{{ props.row.create_date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </el-form-item>
            <el-form-item label="上次更新">
              <span>{{ props.row.update_date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </el-form-item>
            <el-form-item label="备注">
              <span>{{ props.row.remarks }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        type="selection"
        width="45"
      />
      <el-table-column prop="id" label="ID" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="ip" label="管理IP" align="center" width="150%">
        <template slot-scope="scope">
          <span>{{ scope.row.management_ip }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="hostname" label="主机名" width="100%" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.hostname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="SN" align="center" width="120%">
        <template slot-scope="scope">
          <span>{{ scope.row.sn }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="app" align="center" label="应用">
        <template slot-scope="scope">
          <span>{{ scope.row.app }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" align="center" width="150%" label="资产状态">
        <template slot-scope="scope">
          <span>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tags" align="center" label="标签">
        <template slot-scope="scope">
          <template v-for="tag in scope.row.tags">
            <el-tag :key="tag.id" size="small" type="success" style="margin:5px;">{{ tag.name }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['admin','network_edit','network_all'])" type="primary" size="mini" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button v-if="checkPermission(['admin','network_delete','network_all'])" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :page-sizes="[10, 30, 50, 100,999]"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%">
      <el-form ref="dataForm" :model="form" :inline="true" label-position="right" size="small" :rules="rules" label-width="100px">
        <el-form-item label="主机名" prop="hostname">
          <el-input v-model="form.hostname" style="width:150px" />
        </el-form-item>
        <el-form-item label="管理IP" prop="management_ip">
          <el-input v-model="form.management_ip" style="width:150px" />
        </el-form-item>
        <el-form-item label="IP1" prop="ip1">
          <el-input v-model="form.ip1" style="width:150px" />
        </el-form-item>
        <el-form-item label="IP2" prop="ip2">
          <el-input v-model="form.ip2" style="width:150px" />
        </el-form-item>
        <el-form-item label="资产状态" prop="status">
          <el-select v-model="form.status" style="width:150px" placeholder="请选择">
            <el-option
              v-for="item in assetsStatusDict"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资产型号" prop="model">
          <el-input v-model="form.model" style="width:150px" />
        </el-form-item>
        <el-form-item label="资产SN" prop="sn">
          <el-input v-model="form.sn" style="width:150px" />
        </el-form-item>
        <el-form-item label="资产品牌" prop="brand">
          <el-input v-model="form.brand" style="width:150px" />
        </el-form-item>
        <el-form-item label="认证类型" prop="auth_type">
          <el-select v-model="form.auth_type" style="width:150px" placeholder="请选择">
            <el-option
              v-for="item in auth_type_dict"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" style="width:150px" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" style="width:150px" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" style="width:150px" />
        </el-form-item>
        <el-form-item label="设备类型" prop="device_type">
          <el-select v-model="form.device_type" style="width:150px" placeholder="请选择">
            <el-option
              v-for="item in deviceTypeDict"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="管理网段" prop="management_segment">
          <el-input v-model="form.management_segment" style="width:150px" />
        </el-form-item>
        <el-form-item label="上联设备" prop="up_device">
          <el-input v-model="form.up_device" style="width:150px" />
        </el-form-item>
        <el-form-item label="上联端口" prop="up_link_port">
          <el-input v-model="form.up_link_port" style="width:150px" />
        </el-form-item>
        <el-form-item label="应用" prop="app">
          <el-input v-model="form.app" style="width:150px" />
        </el-form-item>
        <el-form-item label="IDC机房" prop="idc">
          <el-select v-model="form.idc" placeholder="请选择" style="width:150px">
            <el-option
              v-for="item in idc_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机柜" prop="cabinet">
          <el-input v-model="form.cabinet" style="width:150px" />
        </el-form-item>
        <el-form-item label="WEB管理" prop="web_url">
          <el-input v-model="form.web_url" style="width:150px" />
        </el-form-item>
        <el-form-item label="系统版本" prop="os_version">
          <el-input v-model="form.os_version" style="width:150px" />
        </el-form-item>
        <el-form-item label="上架日期" prop="shelves_date">
          <el-date-picker
            v-model="form.shelves_date"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="资产标签" prop="tags">
          <el-select v-model="form.tags" style="width:120%;" multiple placeholder="请选择">
            <el-option
              v-for="item in tags_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维保日期" prop="maintenance_date">
          <el-date-picker
            v-model="form.maintenance_date"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" style="width:100%;" rows="1" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission'
import { getTags } from '@/api/tags'
import { getDictByKey } from '@/api/dict'
import FHeader from './components/FilterHeader'
import clip from '@/utils/clipboard'
import { getND, delND, addND, editND } from '@/api/network'
import { getIdc } from '@/api/idc'
export default {
  name: 'Server',
  components: { Pagination, FHeader },
  data() {
    return {
      list: null,
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      tags_list: [],
      idc_list: [],
      assetsStatusDict: [],
      deviceTypeDict: [],
      auth_type_dict: [],
      listLoading: true,
      form: {
        id: '',
        port: '22',
        tags: []
      },
      rules: {
        status: [
          { required: true, message: '请选择资产状态', trigger: 'blur' }
        ],
        device_type: [
          { required: true, message: '请选择设备类型', trigger: 'blur' }
        ]
      },
      listQuery: {
        page: 1,
        limit: 10,
        search: undefined
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.getList()
      this.getTags()
      this.getIdc()
      this.getDicts()
    })
  },
  methods: {
    checkPermission,
    getIdc() {
      getIdc().then(response => {
        this.idc_list = response
      })
    },
    getDicts() {
      const key = [
        'AUTH_TYPE',
        'ASSETS_STATUS',
        'DEVICE_TYPE'
      ]
      getDictByKey(key).then(response => {
        for (const i of response) {
          if (i.ASSETS_STATUS != null) { this.assetsStatusDict = i.ASSETS_STATUS }
          if (i.AUTH_TYPE != null) { this.auth_type_dict = i.AUTH_TYPE }
          if (i.DEVICE_TYPE != null) { this.deviceTypeDict = i.DEVICE_TYPE }
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getTags() {
      getTags().then(response => {
        this.tags_list = response
      })
    },
    getList() {
      getND(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count
        // this.listLoading = false
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 170)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listLoading = true
      this.getList()
    },
    handleSelectionDel() {
      const resultArr = []
      this.multipleSelection.forEach(function(data, index) {
        const result = delND(data.id).catch(err => {
          console.log(err)
        })
        resultArr.push(result)
      })
      Promise.all(resultArr).then((resultArr) => {
        this.handleFilter()
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除此行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delND(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleCopy(text, event) {
      clip(text, event)
    },
    resetForm() {
      this.form = {
        id: '',
        app: '',
        auth_type: '',
        brand: '',
        cabinet: '',
        device_type: '',
        idc: '',
        ip: '',
        maintenance_date: '',
        shelves_date: '',
        management_ip: '',
        model: '',
        os_version: '',
        ip1: '',
        ip2: '',
        password: '',
        port: '22',
        remarks: '',
        sn: '',
        status: '使用中',
        tags: [],
        username: '',
        up_device: '',
        up_link_port: ''
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addND(this.form).then(() => {
            this.resetForm()
            // this.list.unshift(this.temp)
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
            this.dialogFormVisible = false
            this.handleFilter()
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetForm()
      if (row.idc != null) {
        this.form = { ...row, tags: [], idc: [] }
        this.form.idc = row.idc.id
      } else {
        this.form = { ...row, tags: []
        }
      }
      for (const i of row.tags) {
        this.form.tags.push(i.id)
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields()
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editND(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '编辑成功!'
            })
            this.handleFilter()
          })
        }
      })
    }
  }
}
</script>
<style>
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    font-size:12px;
    color: #99a9bf;
  }
  .table-expand span {
    color:#606266;
    font-size:12px
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 25%;
  }
</style>
